/**
*  \file    ssub.h
*
*  \brief   this module contains functions to calculate the difference of two values without overflow.
*           in case of an overflow, the data type limit will be returned.
*
*  \author  Francesco D'Aprea <francesco.daprea@linde-mh.de>
*           Yingqin Wu <yingqin.wu@linde-china.com>
*/

#ifndef SSUB_H_INCLUDED
#define SSUB_H_INCLUDED

/*================================================[ public includes  ]================================================*/
#include "../cfg/prj.h"

/*================================================[ public defines   ]================================================*/

#define SATURATED_SUB(T_VAL) \
   if ( val > (T_VAL)( sub + T_VAL##_MIN ) ) \
   { \
      return (T_VAL)(val - sub); \
   } \
   else \
   { \
      return T_VAL##_MIN; \
   }

/* saturated sub */
STATIC_INLINE U8  saturated_sub_U8( U8 val, U8 sub )
{
   SATURATED_SUB( U8 )
}

STATIC_INLINE U16 saturated_sub_U16( U16 val, U16 sub )
{
   SATURATED_SUB( U16 )
}

STATIC_INLINE U32 saturated_sub_U32( U32 val, U32 sub )
{
   SATURATED_SUB( U32 )
}


#ifdef U64_MAX
/**
*  Saturated subtraction function for U64
*
*  The function saturated_sub_U64 subtract the passed value as long as this does not overflow,
*  and returns it. if it is overflow U64_MIN will be return.
*
*   \param val  minuend
*   \param sub  subtrahend
*
*   \return The difference or U64_MIN .
*/
STATIC_INLINE U64 saturated_sub_U64( U64 val, U64 sub )
{
   SATURATED_SUB( U64 )
}
#endif

STATIC_INLINE S8  saturated_sub_S8( S8 val, U8 sub )
{
   SATURATED_SUB( S8 )
}

STATIC_INLINE S16 saturated_sub_S16( S16 val, U16 sub )
{
   SATURATED_SUB( S16 )
}

STATIC_INLINE S32 saturated_sub_S32( S32 val, U32 sub )
{
   SATURATED_SUB( S32 )
}

/*================================================[ public datatypes ]================================================*/

/*================================================[ public variables ]================================================*/

/*================================================[ public functions ]================================================*/


/*====================================================================================================================*/

#endif

/***********************************************************************************************************************
*                             Copyright 2010 Linde Material Handling. All rights reserved.                             *
***********************************************************************************************************************/
